<template>
	<view class="ff-page-save">
		<slot name="default" :data="data">{{data}}</slot>
	</view>
</template>

<script>
	export default {
		name: "ff-page-save",
		components: {},
		data() {
			return {
				data: {},
				originalData: {},
				loadDataUUId: null,
				submitUUId: null,
			};
		},
		computed: {
			loading(){
				return {
					open:function(){
						this.$parent.$parent.open();
					}.bind(this),
					close:function(){
						this.$parent.$parent.close();
					}.bind(this),
				}
			},
		},
		mounted() {
			this.loadData();
		},
		methods: {
			//获取数据
			loadData() {
				if (this.submitUUId != null) {
					console.log("loadData 数据保存中不能重新加载");
					return;
				}
				let uuid = this.$ff.util.guid();
				this.loadDataUUId = uuid;
				this.loading.open();
				this.$emit('loadData', {
					complete: (data = {}) => {
						if (this.loadDataUUId != uuid) {
							console.log("loadData 当前请求已经被丢弃");
							return;
						}
						this.loadDataUUId = null;
						this.data = JSON.parse(JSON.stringify(data));
						this.originalData = JSON.parse(JSON.stringify(data));
						this.loading.close();
					},
					error: (msg = "获取数据失败, 请重新请求", code = 500) => {
						if (this.loadDataUUId != uuid) {
							console.log("loadData 当前请求已经被丢弃");
							return;
						}
						this.loadDataUUId = null;
						this.loading.close();
					}
				});
			},
			//保存
			submit() {
				if (this.loadDataUUId != null) {
					console.log("submit 保存失败数据正在被重新加载");
					return;
				}
				if (this.submitUUId != null) {
					console.log("submit 重复请求已经被丢弃");
					return;
				}
				let uuid = this.$ff.util.guid();
				this.submitUUId = uuid;
				this.loading.open();
				this.$emit('submit', this.data, {
					complete: (data = undefined) => {
						if (this.submitUUId != uuid) {
							console.log("submit 当前请求已经被丢弃");
							return;
						}
						this.submitUUId = null;
						if (data != undefined) {
							this.data = JSON.parse(JSON.stringify(data));
							this.originalData = JSON.parse(JSON.stringify(data));
							this.loading.close();
						} else {
							this.loadData();
						}
					},
					error: (msg = "获取数据失败, 请重新请求", code = 500) => {
						if (this.submitUUId != uuid) {
							console.log("submit 当前请求已经被丢弃");
							return;
						}
						this.submitUUId = null;
						this.loading.close();
					}
				});
			},
			reset() {
				if (this.loadDataUUId != null) {
					console.log("reset 重置失败数据正在被重新加载");
					return;
				}
				if (this.submitUUId != null) {
					console.log("reset 重置失败数据正在被提交");
					return;
				}
				this.data = JSON.parse(JSON.stringify(this.originalData));
			},
		}
	}
</script>

<style>
	ff-page-save {
		width: 100%;
		height: 100%;
		overflow: hidden;
	}

	.ff-page-save {
		width: inherit;
		height: inherit;
		overflow: hidden;
	}
</style>